package test

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.TypeReference
import com.alibaba.fastjson.annotation.JSONField

class FastJsonTestMain(
    @JSONField(name = "nickName")
    var name: String = "小明",
    var age: Int = 12,
    var sex: String = "男生"
) {
    companion object {
        @JvmStatic
        fun funSimpleTransform() {
            val fastJson = FastJsonTestMain()
            val str = JSON.toJSONString(fastJson)
            val fastJson2 = JSON.parseObject(str, FastJsonTestMain::class.java)

            println("str = $str")
            println("fastJson2 = $fastJson2, (fastJson2 is FastJsonTestMain) is ${fastJson2 is FastJsonTestMain}")
            println()
        }

        @JvmStatic
        fun funCollectionTransform() {
            val array1 = arrayOf(FastJsonTestMain(), FastJsonTestMain("小红", 13, "女生"))
            val strArray1 = JSON.toJSONString(array1)
            val array2 = JSON.parseObject(strArray1, Array<FastJsonTestMain>::class.java)

            println("strArray1 = $strArray1")
            println("array2 = $array2, (array2 is Array<FastJsonTestMain>) is ${(array2 is Array<FastJsonTestMain>)}")
            println()

            val list1 = listOf(FastJsonTestMain(), FastJsonTestMain("小红", 13, "女生"))
            val strList1 = JSON.toJSONString(list1)
            val list2 = JSON.parseObject(strArray1, object : TypeReference<List<FastJsonTestMain>>() {})

            println("strList1 = $strList1")
            println("list2 = $array2, (list2 is List<FastJsonTestMain>) is ${(list2 is List<FastJsonTestMain>)}")
            println()
        }

        fun funAnnotation() {
            val str = "{\"age\":12,\"name\":\"小莉0\",\"nickName\":\"小莉1\",\"sex\":\"女生\"}"
            val value = JSON.parseObject(str, FastJsonTestMain::class.java)
            println("value name = ${value.name}, age = ${value.age}, sex = ${value.sex}")
            println()

            val str2 = "{\"age\":12,\"nickName\":\"小莉1\",\"sex\":\"女生\"}"
            val value2 = JSON.parseObject(str2, FastJsonTestMain::class.java)
            println("value2 name = ${value2.name}, age = ${value2.age}, sex = ${value2.sex}")
            println()
        }
    }
}

fun main() {
//    FastJsonTestMain.funSimpleTransform()
//    FastJsonTestMain.funCollectionTransform()
    FastJsonTestMain.funAnnotation()
}